package com.wdl.fmnew.core.net.utils;

import com.wdl.fmnew.core.net.callback.ApiListener;
import com.wdl.fmnew.core.utils.GsonUtils;
import com.wdl.fmnew.core.net.bean.ApiCommonResultT;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by wdl on 2017/9/18.
 */

public class NetUtils {

    public static <T> ApiCommonResultT getCommonResultT(String json, Class<T> clazz) {
        ApiCommonResultT<T> apiCommonT = null;
        JSONObject jsonObject;
        try {
            apiCommonT = new ApiCommonResultT<>();

            jsonObject = new JSONObject(json);
            int code = jsonObject.getInt("code");
            String msg = jsonObject.getString("message");
            String data = "";
            try {
                data = jsonObject.getString("datas");
            } catch (Exception e) {
                e.printStackTrace();
            }

            apiCommonT.setDatas(GsonUtils.fromJsonArray(data.indexOf("[") != 0 ? ("[" + data + "]") : data, clazz));
            apiCommonT.setCode(code);
            apiCommonT.setMessage(msg);
        } catch (JSONException e) {
            e.printStackTrace();
            apiCommonT = null;
        } finally {
            jsonObject = null;
        }

        return apiCommonT;
    }

    public static boolean handResponseCode(int code) {
        if (code == 200)
            return true;
        return false;
    }


    public static <T> void httpRequest(Observable observable, final Class clazz, final ApiListener<T> apiListener) {

        observable
                .map(new Function<String, ApiCommonResultT>() {
                    @Override
                    public ApiCommonResultT apply(@NonNull String strResult) throws Exception {
                        return getCommonResultT(strResult, clazz);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApiCommonResultT>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull ApiCommonResultT resultT) {
                        if (resultT == null) {
                            if (apiListener != null)
                                apiListener.onError(new Exception("数据解析异常"), "数据解析异常");
                        } else {
                            if (handResponseCode(resultT.getCode())) {
                                if (apiListener != null)
                                    apiListener.onSucess(resultT.getDatas());
                            } else {
                                if (apiListener != null)
                                    apiListener.onError(new Exception("api返回错误"), resultT.getMessage());
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (apiListener != null) {
                            System.out.println("服务器异常：" + e.toString());
                            apiListener.onError(e, "服务器异常");
                            apiListener.onComplted();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (apiListener != null)
                            apiListener.onComplted();
                    }
                });

    }


}
